// ==UserScript==
// @name         微信文章内容获取器
// @namespace    http://tampermonkey.net/
// @version      0.3
// @description  获取微信文章的纯文本内容
// @author       George Cai
// @match        https://mp.weixin.qq.com/*
// @grant        GM.xmlHttpRequest
// ==/UserScript==

(function() {
    'use strict';

    // 创建UI界面
    function createUI() {
        const container = document.createElement('div');
        container.style.position = 'fixed';
        container.style.bottom = '20px';
        container.style.right = '10px';
        container.style.zIndex = '9999';
        container.style.display = 'flex';
        container.style.flexDirection = 'column';
        container.style.gap = '5px';
        container.style.backgroundColor = 'white';
        container.style.padding = '10px';
        container.style.borderRadius = '4px';
        container.style.boxShadow = '0 2px 10px rgba(0,0,0,0.1)';

        // 单个链接输入
        const input = document.createElement('input');
        input.type = 'text';
        input.placeholder = '输入文章链接';
        input.style.padding = '8px';
        input.style.width = '200px';
        input.style.borderRadius = '4px';
        input.style.border = '1px solid #ddd';

        // 单个链接获取按钮
        const button = document.createElement('button');
        button.innerHTML = '获取文章内容';
        button.style.padding = '10px';
        button.style.backgroundColor = '#07C160';
        button.style.color = 'white';
        button.style.border = 'none';
        button.style.borderRadius = '4px';
        button.style.cursor = 'pointer';
        button.style.marginBottom = '10px';
        
        button.addEventListener('click', () => {
            const url = input.value.trim();
            if (url) {
                fetchArticleContent(url);
            } else {
                alert('请输入文章链接');
            }
        });

        // CSV文件上传
        const fileContainer = document.createElement('div');
        fileContainer.style.display = 'flex';
        fileContainer.style.flexDirection = 'column';
        fileContainer.style.gap = '5px';
        fileContainer.style.marginTop = '10px';
        fileContainer.style.borderTop = '1px solid #ddd';
        fileContainer.style.paddingTop = '10px';

        const fileInput = document.createElement('input');
        fileInput.type = 'file';
        fileInput.accept = '.csv';
        fileInput.style.fontSize = '12px';

        const batchButton = document.createElement('button');
        batchButton.innerHTML = '批量获取文章';
        batchButton.style.padding = '10px';
        batchButton.style.backgroundColor = '#1989fa';
        batchButton.style.color = 'white';
        batchButton.style.border = 'none';
        batchButton.style.borderRadius = '4px';
        batchButton.style.cursor = 'pointer';

        // 进度显示
        const progress = document.createElement('div');
        progress.style.fontSize = '12px';
        progress.style.color = '#666';
        progress.style.marginTop = '5px';

        batchButton.addEventListener('click', () => {
            if (fileInput.files.length === 0) {
                alert('请选择CSV文件');
                return;
            }
            
            const file = fileInput.files[0];
            const reader = new FileReader();
            
            reader.onload = async function(e) {
                const text = e.target.result;
                const lines = text.split('\n');
                const headers = lines[0].split(',').map(h => h.trim().toLowerCase());
                const linkIndex = headers.indexOf('link');
                
                if (linkIndex === -1) {
                    alert('CSV文件中未找到link列');
                    return;
                }

                const links = [];
                for (let i = 1; i < lines.length; i++) {
                    const columns = lines[i].split(',');
                    if (columns.length > linkIndex) {
                        const link = columns[linkIndex].trim().replace(/^"|"$/g, '');
                        if (link) links.push(link);
                    }
                }

                progress.textContent = `共找到 ${links.length} 个链接`;
                
                // 批量处理链接
                for (let i = 0; i < links.length; i++) {
                    progress.textContent = `正在处理: ${i + 1}/${links.length}`;
                    await new Promise(resolve => {
                        fetchArticleContent(links[i], resolve);
                        // 添加延时避免请求过快
                        setTimeout(resolve, 2000);
                    });
                }

                progress.textContent = `处理完成，共处理 ${links.length} 个链接`;
            };

            reader.readAsText(file);
        });

        fileContainer.appendChild(fileInput);
        fileContainer.appendChild(batchButton);
        fileContainer.appendChild(progress);

        container.appendChild(input);
        container.appendChild(button);
        container.appendChild(fileContainer);
        document.body.appendChild(container);
    }

    // 修改fetchArticleContent函数，添加callback参数
    function fetchArticleContent(url, callback = null) {
        const savedData = JSON.parse(localStorage.getItem('wechat_auth_data') || '{}');
        const cookies = savedData.raw_set_cookies;

        if (!cookies) {
            alert('请先使用Cookie获取器获取cookies！');
            if (callback) callback();
            return;
        }

        GM.xmlHttpRequest({
            method: 'GET',
            url: url,
            headers: {
                'Cookie': cookies,
                'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'Cache-Control': 'no-cache'
            },
            onload: function(response) {
                try {
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(response.responseText, 'text/html');

                    const content = {
                        title: '',
                        author: '',
                        publishTime: '',
                        content: ''
                    };

                    // 提取标题
                    const titleElement = doc.getElementById('activity-name');
                    if (titleElement) {
                        content.title = titleElement.innerText.trim();
                    }

                    // 提取作者
                    const authorElement = doc.getElementById('js_name');
                    if (authorElement) {
                        content.author = authorElement.innerText.trim();
                    }

                    // 提取发布时间
                    const timeElement = doc.getElementById('publish_time');
                    if (timeElement) {
                        content.publishTime = timeElement.innerText.trim();
                    }

                    // 提取正文内容
                    const contentElement = doc.getElementById('js_content');
                    if (contentElement) {
                        // 获取所有文本节点
                        const textNodes = [];
                        const walk = document.createTreeWalker(
                            contentElement,
                            NodeFilter.SHOW_TEXT,
                            {
                                acceptNode: function(node) {
                                    if (node.parentElement.tagName === 'SCRIPT' || 
                                        node.parentElement.tagName === 'STYLE') {
                                        return NodeFilter.FILTER_REJECT;
                                    }
                                    return node.textContent.trim() ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
                                }
                            }
                        );

                        let node;
                        while (node = walk.nextNode()) {
                            textNodes.push(node.textContent.trim());
                        }

                        content.content = textNodes.join('\n');
                    }

                    // 保存内容
                    saveContent(content);
                    if (callback) callback();

                } catch (error) {
                    console.error('解析文章失败:', error);
                    alert('解析文章失败，请查看控制台了解详情');
                    if (callback) callback();
                }
            },
            onerror: function(error) {
                console.error('请求失败:', error);
                alert('请求失败，请查看控制台了解详情');
                if (callback) callback();
            }
        });
    }

    // 保存内容为文本文件
    function saveContent(content) {
        const textContent = [
            `标题：${content.title}`,
            `作者：${content.author}`,
            `发布时间：${content.publishTime}`,
            '正文：',
            content.content
        ].join('\n\n');

        const blob = new Blob(['\ufeff' + textContent], { type: 'text/plain;charset=utf-8' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        const fileName = content.title.replace(/[\\/:*?"<>|]/g, '_') || 'article';
        a.download = `${fileName}.txt`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }

    // 等待页面加载完成后创建UI
    window.addEventListener('load', createUI);
})(); 